package UDP;

import java.io.IOException;
import java.net.BindException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.nio.charset.StandardCharsets;

/**
 * 功能描述
 *基于UDP的回显服务器
 * @author wileda
 * @date 2023/02/19  12:08
 */
public class UDPEchoServer {
    //声明一个提供UDP服务的对象
    private DatagramSocket socket;

    //通过构造方法指定服务的端口号
    public UDPEchoServer(int port) throws SocketException {
        //校验端口
        if(port < 1 || port > 65535){
            throw new BindException("端口号建议在1025 - 65535之间");
        }
        //实例化UDP服务
        this.socket = new DatagramSocket(port);
    }

    /**
     * 启动服务
     */
    public void start() throws IOException {
        System.out.println("启动服务成功");
        //循环处理请求
        while(true){
            // 1. 使用DatagramPacket来接收用户的请求
            DatagramPacket requestPacket = new DatagramPacket(new byte[1024], 1024);
            // 2. 接收数据
            socket.receive(requestPacket);
            // 3. 解析接收到的数据
            String request = new String(requestPacket.getData(),0, requestPacket.getLength(),"UTF-8");
            // 4. 根据请求来计算响应
            String response =  process(request);
            // 5. 使用DatagramPacket封装响应数据
            DatagramPacket responsePacket = new DatagramPacket(response.getBytes(StandardCharsets.UTF_8),
                    response.getBytes().length, requestPacket.getSocketAddress());
            // 6.发送响应
            socket.send(responsePacket);
            // 7. 打印日志
            System.out.printf("[%s:%d] request = %s, response = %s\n", requestPacket.getAddress().toString(),
                    requestPacket.getPort(), request, response);
        }
    }

    protected String process(String request) {
        return request;
    }


    public static void main(String[] args) throws IOException {
        // 初始化UPD服务端对象
        UDPEchoServer server = new UDPEchoServer(9090);
        // 启动服务
        server.start();
    }
}
